using System;
using System.Data.Linq;
using System.Linq;
using Jobping.ShortUrls.Models;

namespace Jobping.ShortUrls.Models
{
    /// <summary>
    ///     Linq database helper. Bascially this compiles two queries we need for the app.
    /// </summary>
    internal static class ShortUrlDbHelper
    {

        private static Func<DbDataContext, string, Url> GetByLongUrlFunc =
                            CompiledQuery.Compile
                            (
                                (DbDataContext db, string longUrl) =>
                                (from c in db.Urls where c.LongUrl == longUrl select c).FirstOrDefault()
                            );

        private static Func<DbDataContext, string, Url> GetByShortUrlFunc =
                            CompiledQuery.Compile
                            (
                                (DbDataContext db, string shortUrl) =>
                                (from c in db.Urls where c.ShortUrl == shortUrl select c).FirstOrDefault()
                            );

        private static Func<DbDataContext, long, Url> GetMapUrlByIdFunc =
                            CompiledQuery.Compile
                            (
                                (DbDataContext db, long id) =>
                                (from c in db.Urls where c.Id == id select c).FirstOrDefault()
                            );

        // Get
        // Extension Method for our dataContext, used to wrap our ugle compiled function
        internal static Url GetById(this DbDataContext db, long id)
        {
            return GetMapUrlByIdFunc(db, id);
        }

        internal static Url GetByLongUrl(this DbDataContext db, string longUrl)
        {
            return GetByLongUrlFunc(db, longUrl);
        }

        internal static Url GetByShortUrl(this DbDataContext db, string longUrl)
        {
            return GetByShortUrlFunc(db, longUrl);
        }
    }
}
